package com.flower.wx.controller;

import com.flower.wx.handler.WxChatMsgFactory;
import com.flower.wx.handler.WxChatMsgHandler;
import com.flower.wx.util.MessageUtil;
import com.flower.wx.util.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author lavender
 * @version 1.0
 * @date 2024-07-18 22:39
 */
@RestController
@Slf4j
public class CallBackController {



    private String token = "12345";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;


    @GetMapping("callback")
    public String callback(@RequestParam String signature,
                           @RequestParam String timestamp,
                           @RequestParam String nonce,
                           @RequestParam String echostr) {

        log.info("signature:{},timestamp:{},nonce:{},echostr:{}", signature, timestamp, nonce, echostr);

        String sha1 = SHA1.getSHA1(token, timestamp, nonce, "");
        if (sha1.equals(signature)) {
            return echostr;
        }
        return "unknow";
    }


    @PostMapping(value = "callback",produces = "application/xml;charset=UTF-8")
    public String callback1(
            @RequestBody String requestBody,
            @RequestParam String signature,
                           @RequestParam String timestamp,
                           @RequestParam String nonce,
                           @RequestParam(value = "msg_signature",required = false) String msgSignature) {


        log.info("requestBody:{},signature:{},timestamp:{},nonce:{},msgSignature:{}", requestBody, signature, timestamp, nonce, msgSignature);

        String sha1 = SHA1.getSHA1(token, timestamp, nonce, "");

        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        // 发送方
        String userName = msgMap.get("ToUserName");
        String fromUserName = msgMap.get("FromUserName");
        String msgType = msgMap.get("msgType");

        String event = msgMap.get("Event") == null ? "" : msgMap.get("Event");

        StringBuilder sb = new StringBuilder();
        sb.append(msgType);

        if(!StringUtils.isEmpty(event)){
            sb.append(".");
            sb.append(event);
        }


        String msgTypeKey = msgType + "." + event;
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getWxChatMsgHandler(sb.toString());
        String replyContent = wxChatMsgHandler.dealMsg(msgMap);

        return "unknow";
    }
}
